//
//  HNActionCache.m
//  HeroNuts
//
//  Created by Vicky on 6/4/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HNActionCache.h"
#import "cocos2d.h"
#import "HNActorInfoCache.h"


@implementation HNActionCache

#pragma mark HNActionCache - Alloc, Init & Dealloc

static HNActionCache* sharedActionCache_ = nil;

+(id)sharedActionCache
{
	if (!sharedActionCache_)
	sharedActionCache_ = [[HNActionCache alloc] init];
	                 
	return sharedActionCache_;
}

+(id)alloc
{
	NSAssert(sharedActionCache_ == nil, @"Attempted to allocate a second instance of a singleton.");
	return [super alloc];
}

-(id)init
{
	if( (self = [super init]) ) 
	{
		actions_ = [[NSMutableDictionary alloc] initWithCapacity: 20];
	}
	return self;	
}

-(void)dealloc
{	
	[actions_ release];	
	[super dealloc];
}

#pragma mark HNActionCache - loading action resource

-(void)addActionWithFile:(NSString*)plist
{
	[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:plist];
}

#pragma mark HNActionCache - getting

-(id)actionByName:(NSString*)actionType actor:(NSString*)actorType
{
	NSString* key = [NSString stringWithFormat:@"%@_%@",actorType,actionType];
	
	CCAnimate *action = [actions_ objectForKey:key];
	if (action) 
	{
		return action;
	}
	else 
	{
        NSArray *frameNames = [[HNActorInfoCache sharedActorInfoCache] actionFramesByName:actionType actor:actorType];
		if (!frameNames) 
		{
			return nil;
		}
		else 
		{
			NSMutableArray *animFrames = [NSMutableArray array];
			
			for (NSString *name in frameNames) {
				CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:name];
				[animFrames addObject:frame];
			}
			
			CGFloat delay = [[HNActorInfoCache sharedActorInfoCache] frameDelayByActor:actorType];
			CCAnimation *animation = [CCAnimation animationWithFrames:animFrames delay:delay];
			action = [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
			[actions_ setObject:action forKey:key];
			
			return action;
		}
	}
}

@end
